package controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.RejectDAO;
import dao.WarehouseDAO;
import model.Reject;
import model.Warehouse;

/**
 * Servlet implementation class JinhuoController
 */
public class ChuhuoController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ChuhuoController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			String rejectId = request.getParameter("rejectId");
			String rejectCode = request.getParameter("rejectCode");
			String quantity = request.getParameter("quantity");
			String status = "初始";
			String creator = new String(request.getParameter("creator").getBytes("ISO-8859-1"),"UTF-8");
			Date time = new Date();
			String productId = request.getParameter("productId");
			//判断是否可以出货
			Warehouse wr = new WarehouseDAO().getByProductId(productId);
			if(Integer.parseInt(quantity)>wr.getEnableQuantity()){
				System.out.println("库存不足出货失败");
				String message = URLEncoder.encode("库存不足出货失败", "UTF-8");
				response.sendRedirect("./view/error.jsp?errorInfo="+message+"&redirect=./chuhuo.jsp");
			}else{
				if (new RejectDAO().save(
						new Reject(rejectId, rejectCode, Integer.parseInt(quantity), status, creator, time, productId))) {
					// 成功
					int newQuan = wr.getEnableQuantity()- Integer.parseInt(quantity);
					new WarehouseDAO().updateEnableQuantity(newQuan, productId);//更新可用库存
					System.out.println("出货成功");
					String message = URLEncoder.encode("出货成功", "UTF-8");
					response.sendRedirect("./view/error.jsp?errorInfo="+message+"&redirect=./chuhuo.jsp");
				
				} else {
					// 失败
					System.out.println("出货失败");
					String message = URLEncoder.encode("出货失败", "UTF-8");
					response.sendRedirect("./view/error.jsp?errorInfo="+message+"&redirect=./chuhuo.jsp");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			String message = URLEncoder.encode("出货失败", "UTF-8");
			response.sendRedirect("./view/error.jsp?errorInfo="+message+"&redirect=./chuhuo.jsp");
		
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
